package ServerOperation;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Scanner;

import Controllers.RequestManager;
import Entity.Message;

public class DBHandler 
{
	private static  DBHandler Instance = null;
	private String ConfigFileDB = "DBConfig.txt";
	HashMap<Integer,IDBHandler> DBHandlers;
	private Connection conn;
	
	/**
	 * 
	 * @return the connection to the db
	 */
	public Connection getConn() {
		return conn;
	}
	/**
	 *  constructor read configuration file and make connetion to db
	 */
	private DBHandler()
	{
		
		Scanner in=null;
		
		try {
			String Host=null,DB=null,username=null,password=null;
			
			in = new Scanner(new FileReader(ConfigFileDB));
			
			in.useDelimiter(",");
			
			while (in.hasNext())
			{
				Host = in.next();
				DB =  in.next();
				username = in.next();
				password = in.next();
			}
			
			makeConnection(Host,DB,username,password);
		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		DBHandlers = new HashMap<Integer,IDBHandler>();
		DBHandlers.put(1, new DBWorker(getConn()));
		DBHandlers.put(3, new DBInfoSystem(getConn()));
		DBHandlers.put(5, new DBReport(getConn()));
		DBHandlers.put(7, new DBRequest(getConn()));
		DBHandlers.put(9, new DBStatusHistory());
		DBHandlers.put(11, new DBUser(getConn()));
		DBHandlers.put(13, new DBStatistical(getConn()));
		
		
		Statement stat;
		try {
			stat = conn.createStatement();
			String query = "set names utf8";
		    stat.execute(query);
		    System.out.println(stat);
		  //  query = "set character set utf8";
		  //  stat.execute(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	
	/**
	 * 
	 * @return instance for singlton prepses
	 */
	public static DBHandler getInstance()
	{
		if(Instance == null)
		{
			Instance = new DBHandler();	
		}
		return Instance;
	}
	/**
	 * message hnadling sends to the spacific class handle according to the message opcode
	 * @param msg
	 * @return
	 */
	public Message messageHandle(Message msg){
		int op = (msg.getOpCode()/1000);
		System.out.println(op +"op code");
		
		Message retmsg = DBHandlers.get(op).decipherMessage(msg);

		return retmsg;
	}
	
	
	
	/**
	 * making connection to db
	 * @param Host
	 * @param DBName
	 * @param UserName
	 * @param Password
	 * @throws IOException
	 */
	public void makeConnection(String Host,String DBName,String UserName,String Password) throws IOException {
		
		
		try 
		{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
        	
        	System.out.println("SQLException: ");
        	throw new IOException();
        }
        
		
		
		try {

			conn  = DriverManager.getConnection("jdbc:mysql://"+Host+"/"+DBName+"?useUnicode=true&characterEncoding=utf-8",UserName,Password);
	
		} catch (SQLException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
			System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
			throw new IOException();
		}
	
		
		
	}
	/**
	 * disconndects all user that were logged in in the last session
	 */
	public void disconnectAllUser() {
		// TODO Auto-generated method stub
		try {
			Statement stmt = conn.createStatement();
			String Qurery = new String("Update user set userLogged = 0 where userLogged=1");
			stmt.executeUpdate(Qurery);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
